"""
常用数据操作类
"""
import json
import os

import requests


class VisibleDict(dict):
    """
    继承自dict的类，实现更易读的__str__方法，并支持VisibleList。
    """

    def __init__(self, *args, indent=4, **kwargs):
        super().__init__(*args, **kwargs)
        self.indent = indent

    def __str__(self, level=0):
        """
        递归地格式化字典内容。

        Args:
            level (int): 当前缩进级别。

        Returns:
            str: 格式化后的字符串。
        """
        if not self:
            return "{}"

        items = []
        for key, value in self.items():
            if isinstance(value, (VisibleDict, VisibleList)):
                # 递归调用__str__方法格式化嵌套的VisibleDict或VisibleList
                value_str = value.__str__(level + 1)
            else:
                # 格式化其他类型的值
                value_str = repr(value)

            items.append(f"{' ' * (level + 1) * self.indent}\"{key}\": {value_str}")

        return "{\n" + ",\n".join(items) + "\n" + " " * level * self.indent + "}"


class VisibleList(list):
    """
    继承自list的类，实现更易读的__str__方法。
    """

    def __init__(self, *args, indent=4, **kwargs):
        super().__init__(*args, **kwargs)
        self.indent = indent

    def __str__(self, level=0):
        """
        递归地格式化列表内容。

        Args:
            level (int): 当前缩进级别。

        Returns:
            str: 格式化后的字符串。
        """
        if not self:
            return "[]"

        items = []
        for value in self:
            if isinstance(value, (VisibleDict, VisibleList, list, dict)):
                # 递归调用__str__方法格式化嵌套的VisibleDict或VisibleList
                value_str = value.__str__(level + 1)
            else:
                # 格式化其他类型的值
                value_str = repr(value)

            items.append(f"{' ' * (level + 1) * self.indent}{value_str}")

        return "[\n" + ",\n".join(items) + "\n" + " " * level * self.indent + "]"


def formatted(text: str):
    """
    去除多余空行
    :param text:
    :return:
    """
    lines = text.splitlines()
    non_empty_lines = [line for line in lines if line.strip()]
    result = '\n'.join(non_empty_lines)
    return result


def getUserConfig() -> dict:
    try:
        path = os.getcwd().split("moxi_server")[0] + "\\moxi_server\\src\\config\\UserConfig.json"
        with open(path, "r", encoding="utf-8") as file:
            json_data = json.load(file)
            file.close()
            return json_data
    except Exception:
        with open("UserConfig.json", "r", encoding="utf-8") as file:
            json_data = json.load(file)
            file.close()
            return json_data


def getPosition(address: str) -> str | None:
    """
    用于返回高德API的adcode
    :param address: 具体地址
    :return: adcode
    """

    city = None
    for div in ["省", "区", "自治区", "县"]:
        index = address.find(div)
        if index != -1:
            city = address[index + len(div):]

    data = {
        "key": getUserConfig()["amap_api_key"],
        "address": address,
        "city": city
    }
    response = requests.get(
        "https://restapi.amap.com/v3/geocode/geo",
        params=data,
        headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate',
        }).json()
    if response['info'] == 'OK':
        return response['geocodes'][0]['adcode']
    else:
        return None
